{% extends 'base.html' %}
{% load seahub_tags avatar_tags i18n staticfiles %}


{% block sub_title %}{{filename}} - {% endblock %}
{% block viewport %}{% endblock %}

{% block extra_style %}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/file_view_extra.css" />
<style type="text/css">
#view-hd {
    width:100%;
    padding:0 15px 12px;
    border-bottom:1px solid #c9c9c9;
    display:flex;
    justify-content:space-between;
    flex-shrink:0;
}
#file-view {
    border:none;
    border-right:4px solid transparent;
    margin-top:0;
}
#file-discussions {
    width:400px;
}
</style>
{% endblock %}

{% block header_css_class %}hide{% endblock %}
{% block main_class %}ovhd d-flex fd-col{% endblock %}

{% block main_content %}
    <div id="view-hd">
        <div>
            <h2 class="file-view-hd">
                <span class="vam">{{ filename }}</span>
                {% if is_starred %}
                <a id="file-star" class="vam no-deco icon-star" href="#" title="{% trans "starred" %}" aria-label="{% trans "starred" %}"></a>
                {% else %}
                <a id="file-star" class="vam no-deco icon-star-empty" href="#" title="{% trans "unstarred" %}" aria-label="{% trans "unstarred" %}"></a>
                {% endif %}

                {% if is_pro %}
                <img class="file-locked-icon cspt vam {% if not file_locked %}hide{% endif %}" width="16" src="{{ MEDIA_URL }}img/file-locked-32.png" alt="{% trans "locked" %}" title="{% trans "locked" %}" aria-label="{% trans "locked" %}" />
                {% endif %}
            </h2>
            <div class="commit">
                <a href="{% url 'user_profile' latest_contributor %}" class="name vam">{{ latest_contributor|email2nickname }}</a>
                <span class="time vam">{{ last_modified|translate_seahub_time}}</span>
                {% block update_detail %}
                {% if last_commit_id %}
                  <span class="vam">{% trans "updated this file"%}.</span>
                {% endif %}
                {% endblock %}
            </div>
        </div>

        <div class="sf-btn-group file-view-op">
            <a class="sf-btn-group-btn sf-btn-group-btn-first sf-btn-link op-icon sf2-icon-folder" href="{{ SITE_ROOT }}#common/lib/{{ repo.id }}/{{ parent_dir|strip_slash }}" title="{% trans "Open parent folder" %}"></a>

            {% if can_lock_unlock_file %}
                {% if not file_locked %}
                    <button id="lock-file" class="sf-btn-group-btn op-icon sf2-icon-lock" title="{% trans "Lock" %}"></button>
                    <button id="unlock-file" class="sf-btn-group-btn op-icon sf2-icon-unlock hide" title="{% trans "Unlock" %}"></button>
                {% elif locked_by_me %}
                    <button id="unlock-file" class="sf-btn-group-btn op-icon sf2-icon-unlock" title="{% trans "Unlock" %}"></button>
                    <button id="lock-file" class="sf-btn-group-btn op-icon sf2-icon-lock hide" title="{% trans "Lock" %}"></button>
                {% endif %}
            {% endif %}

            {% if not repo.encrypted %}
            {% if request.user.permissions.can_generate_share_link %}
            <button id="share" class="sf-btn-group-btn op-icon sf2-icon-share" data-link="{{ file_shared_link }}" data-token="{{ fileshare.token }}" title="{% trans "Share" %}"></button>
            {% endif %}
            {% endif %}

            {% if file_perm == 'rw' %}
            <a class="sf-btn-group-btn sf-btn-link op-icon sf2-icon-clock" id="history" href="{% url 'file_revisions' repo.id %}?p={{ path|urlencode }}" title="{% trans "History" %}"></a>
            {% endif %}

            {% if request.user.is_authenticated and can_edit_file %}
                {% block edit_file %}
                {% endblock %}
            {% endif %}

            {% if enable_file_comment %}
            <a class="sf-btn-group-btn sf-btn-link op-icon sf2-icon-download" href="?dl=1" id="download" title="{% trans "Download"%}"></a>
            <button id="discuss" class="sf-btn-group-btn sf-btn-group-btn-last op-icon sf2-icon-msgs" title="{% trans "Comment" %}"></button>
            {% else %}
            <a class="sf-btn-group-btn sf-btn-group-btn-last sf-btn-link op-icon sf2-icon-download" href="?dl=1" id="download" title="{% trans "Download"%}"></a>
            {% endif %}

        </div>

    </div>

    <div class="d-flex flex-auto ovhd"> {# 'ovhd' is for Firefox #}
        <div id="file-view" class="flex-1 ov-auto {% block file_view_extra_class %}{% endblock %}">
          {% if err %}
            <div id="file-view-tip">
            {% if err != 'invalid extension' %}
                <p class="error">{{ err }}</p>
            {% endif %}
            </div>
          {% else %}
              {% block file_view %}{% endblock %}
          {% endif %}
        </div>
        <div id="file-discussions" class="comments-panel" style="display:none;"></div>
    </div>

    {% include "snippets/file_share_popup.html" %}

    <div id="side-toolbar">
        <ul class="side-toolbar">
            <li class="item hide" id="back-to-top" title="{% trans "Back to top" %}"><img src="{{MEDIA_URL}}img/top.png" alt="{% trans "top" %}" /></li>
        </ul>
    </div>

<script type="text/template" id="discussion-panel-tmpl">
    <div class="comments-panel-hd file-discussions-hd ovhd">
        <a href="#" title="{% trans "Close" %}" aria-label="{% trans "Close" %}" class="sf-popover-close js-close sf2-icon-x1 op-icon"></a>
        <h3 class="comments-panel-title">{% trans "Comments" %}</h3>
    </div>
    <div class="comments-panel-con file-discussions-con">
        <div class="loading-icon loading-tip"></div>
        <ul class="file-discussion-list hide"></ul>
        <p class="no-discussion-tip hide">{% trans "No comment yet." %}</p>
        <p class="error hide"></p>
    </div>
    <div class="comments-panel-footer file-discussions-footer">
        <form action="" method="post" class="msg-form">
            <img src="{% avatar_url request.user 64 %}" alt="" width="32" class="avatar-circle fleft" />
            <div class="msg-body">
                <textarea name="message" placeholder="{% trans "Add a comment..." %}" title="{% trans "Add a comment..." %}" aria-label="{% trans "Add a comment..." %}" class="msg-input"></textarea>
                <p class="error hide"></p>
                <button type="submit" class="submit msg-submit">{% trans "Submit" %}</button>
            </div>
        </form>
    </div>
</script>
<script type="text/template" id="discussion-tmpl">
<li class="msg ovhd">
    <img src="<%= avatar_url %>" alt="" width="32" class="avatar-circle fleft" />
    <div class="msg-body">
        <div class="ovhd">
            <a class="msg-username ellipsis" title="<%- user_name %>" href="<%= user_profile_url %>"><%- user_name %></a>
            <span class="msg-time" title="<%- time %>"><%- time_from_now %></span>
            <div class="msg-ops fright vh">
                <a class="msg-op sf2-icon-reply op-icon js-reply-msg" title="{% trans "Reply" %}" aria-label="{% trans "Reply" %}" href="#" data-username="<%- user_name %>"></a>
                <% if (can_delete_msg) { %>
                    <a class="msg-op sf2-icon-delete op-icon js-del-msg" title="{% trans "Delete" %}" aria-label="{% trans "Delete" %}" href="#" data-id="<%= id %>"></a>
                <% } %>
            </div>
        </div>
        <div class="msg-content"><%= content_marked %></div>
    </div>
</li>
</script>

{% endblock %}

{% block extra_script %}
<script type="text/javascript" src="{% static "scripts/lib/jquery-ui.min.js" %}"></script> {# for 'tabs' used in share popup #}
<script type="text/javascript" src="{% static "scripts/lib/underscore.js" %}"></script>
<script type="text/javascript" src="{% static "scripts/lib/moment-with-locales.min.js" %}"></script>
<script type="text/javascript" src="{% static "scripts/lib/marked.min.js" %}"></script>
{% if highlight_keyword %}
<script type="text/javascript" src="{{ MEDIA_URL }}js/findAndReplaceDOMText.js"></script>
{% endif %}
<script type="text/javascript">
// download
$(function() {
    var dld_url = $('#download').attr('href');
    $('#file-view-tip').append('<a href="' + dld_url + '" class="sf-btn-link big-btn-link">' + "{% trans "Download" %}" + '</a>');
});

// share link
{% include "snippets/shared_link_js.html" %}
$('#share').on('click', function() {
    var op = $(this),
        name = "{{filename|escapejs}}",
        path = "{{path|escapejs}}",
        aj_data = {
            'repo_id': "{{ repo.id }}",
            'path': path
        },
        type = 'f',
        cur_path = path.substr(0, path.length - name.length);

    showSharePopup(op, name, aj_data, type, cur_path);

    return false;
});


// star file
$('#file-star').on('click', function() {
    var op_icon = $(this), url_base;
    url_base = '{% url "starredfiles" %}';

    if (op_icon.hasClass('icon-star-empty')) {
        // star the file
        $.ajax({
            url: url_base,
            cache: false,
            dataType: 'json',
            type: 'POST',
            beforeSend: prepareCSRFToken,
            data: {
                'repo_id': "{{ repo.id }}",
                'p': "{{ path|escapejs }}"
            },
            success:function(data) {
                op_icon.toggleClass('icon-star-empty icon-star');
            },
            error: ajaxErrorHandler
        });
    } else {
        // unstar
        $.ajax({
            url: url_base + '?p=' + e("{{path|escapejs}}") + '&repo_id=' + "{{ repo.id }}",
            cache: false,
            dataType: 'json',
            type: 'DELETE',
            beforeSend: prepareCSRFToken,
            success:function(data) {
                op_icon.toggleClass('icon-star-empty icon-star');
            },
            error: ajaxErrorHandler
        });
    }

    return false;
});

{% if can_lock_unlock_file %}
// lock/unlock file
$('#lock-file, #unlock-file').on('click', function() {
    var op = $(this).attr('id') == 'lock-file' ? 'lock' : 'unlock',
        path = '{{path|escapejs}}';
    $.ajax({
        url: '{% url 'api-v2.1-file-view' repo.id %}' + '?p=' + encodeURIComponent(path),
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'operation': op},
        success: function() {
            $('#lock-file, #unlock-file, .file-locked-icon').toggleClass('hide');
        },
        error: ajaxErrorHandler
    });
});
{% endif %}

// set 'side toolbar' position
function setToolbarPos() {
    var toolbar = $('#side-toolbar');

    // set toolbar pos
    toolbar.css({'top': ($(window).height() - toolbar.outerHeight())/2});
}
(function () {
    var to_top = $('#back-to-top');
    to_top.on('click', function() {
        $(window).scrollTop(0);
    });
    $(window).on('scroll', function() {
        if ($(window).scrollTop() > 0) {
            to_top.show();
        } else {
            to_top.hide();
        }
    });
})();
$(window).on('load resize', setToolbarPos);

{% if highlight_keyword %}
var ref_list = document.referrer.split('?');
// referrer is 'search result' page, i.e, '{{SITE_ROOT}}search/?q=xx..'
if (ref_list.length > 1 && ref_list[0].indexOf('search') > 0) {
    var search_params = ref_list[1].split('&');
    var search_keyword = search_params[0].substr(2); // get 'xx' from 'q=xx'

    var highlight_kw = function(hl_area) { // 'hl_area': a node
        findAndReplaceDOMText(hl_area, {
            find: new RegExp(search_keyword, 'gim'),
            replace: function(portion, match) { // portion is a part of a match
                var node = document.createElement('span');
                node.style.background = '#ffe761';
                node.innerHTML = portion.text; // portion is an object
                return node;
            }
        });
    };
}

$(window).on('load', function() {
    if (highlight_kw) {
        // hl kw in file title
        highlight_kw($('.file-view-hd span')[0]);

        // hl kw in file content
        if ('{{filetype}}' == 'Markdown') {
            highlight_kw($('#file-view')[0]);
        }
        if ('{{fileext}}' == 'text' || '{{fileext}}' == 'txt') {
            setTimeout(function(){ highlight_kw($('.CodeMirror')[0]); }, 500);
        }
    }
});
{% endif %}


// file discussion
var fileDiscussions = {

    $el: $('#file-discussions'),
    tmpl: _.template($('#discussion-panel-tmpl').html()),

    init: function() {
        var _this = this;

        this.setLocale();

        // events
        this.$el.on('click', '.js-close', function() {
            _this.hide();
            return false;
        });
        this.$el.on('mouseenter', '.msg', function() {
            $(this).addClass('hl').find('.msg-ops').removeClass('vh');
        });
        this.$el.on('mouseleave', '.msg', function() {
            $(this).removeClass('hl').find('.msg-ops').addClass('vh');
        });
        this.$el.on('click', '.js-reply-msg', function() {
            _this.replyTo($(this).attr('data-username'));
            return false;
        });
        this.$el.on('click', '.js-del-msg', function() {
            _this.delOne({
                id: $(this).attr('data-id'),
                $el: $(this).closest('.msg')
            });
            return false;
        });
        this.$el.on('submit', '.msg-form', function() {
            _this.formSubmit();
            return false;
        });

    },

    setLocale: function() {
        var lang_code = '{{LANGUAGE_CODE}}';
        var m_lang_code;
        if (lang_code == 'en') {
            m_lang_code = 'en-gb';
        } else if (lang_code == 'es-ar' || lang_code == 'es-mx') {
            m_lang_code = 'es';
        } else {
            m_lang_code = lang_code;
        }
        moment.locale(m_lang_code);
    },

    render: function () {
        this.$el.html($(this.tmpl()));

        this.$listContainer = $('.file-discussion-list', this.$el);
        this.$emptyTip = $('.no-discussion-tip', this.$el);
        this.$loadingTip = $('.loading-tip', this.$el);
        this.$conError = $('.file-discussions-con .error', this.$el);
        this.$msgInput = $('[name="message"]', this.$el);
    },

    collectionUrl: '{% url "api2-file-comments" repo.id %}?p='
        + e('{{path|escapejs}}') + '&avatar_size=64',

    show: function() {
        this.render();
        this.$el.show();

        // pdf file view with pdf.js; text file view; #file-view-tip
        $('#pdf, .CodeMirror, #file-view-tip').css({'width':'auto', 'margin':'0 10px'});
        // encoding selector
        $('#file-enc-cont').css({'width': 'auto', 'margin-right':'10px'});

        this.getContent();
    },

    hide: function() {

        // pdf file view with pdf.js; text file view; #file-view-tip
        // encoding selector
        $('#pdf, .CodeMirror, #file-enc-cont, #file-view-tip').removeAttr('style');

        this.$el.empty().hide();
    },

    getContent: function() {
        var _this = this;
        $.ajax({
            url: this.collectionUrl,
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function(data) {
                var comments = data.comments;
                if (comments.length > 0) {
                    $(comments).each(function(index, item) {
                        _this.addOne(item);
                    });
                    _this.$listContainer.show();
                    _this.scrollConToBottom();
                } else {
                    _this.$emptyTip.show();
                }
            },
            error: function(xhr) {
                var err_msg;
                if (xhr.responseText) {
                    err_msg = JSON.parse(xhr.responseText).error_msg;
                } else {
                    err_msg = "{% trans "Failed. Please check the network." %}";
                }
                _this.$conError.html(err_msg).show();
            },
            complete: function() {
                _this.$loadingTip.hide();
            }
        });
    },

    formSubmit: function() {
        var _this = this;
        var $formError = $('.msg-form .error', this.$el);
        var $submitBtn = $('[type="submit"]', this.$el)
        var msg = $.trim(this.$msgInput.val());

        if (!msg) {
            return false;
        }

        $formError.hide();
        disable($submitBtn);
        $.ajax({
            url: this.collectionUrl,
            type: 'POST',
            cache: false,
            dataType: 'json',
            beforeSend: prepareCSRFToken,
            data: {'comment': msg},
            success: function(data) {
                _this.$msgInput.val('');
                _this.addOne(data);
                if (_this.$emptyTip.is(':visible')) {
                    _this.$emptyTip.hide();
                    _this.$listContainer.show();
                }
                _this.scrollConToBottom();
            },
            error: function(xhr) {
                var err_msg;
                if (xhr.responseText) {
                    err_msg = JSON.parse(xhr.responseText).error_msg;
                } else {
                    err_msg = "{% trans "Failed. Please check the network." %}";
                }
                $formError.html(err_msg).show();
            },
            complete: function() {
                enable($submitBtn);
            }
        });
    },

    itemTmpl: _.template($('#discussion-tmpl').html()),

    addOne: function(obj) {
        var can_delete_msg = false;
        var is_repo_owner = {% if is_repo_owner %}true{% else %}false{% endif %};
        if (is_repo_owner ||
            obj.user_email == '{{request.user|escapejs}}') {
            can_delete_msg = true;
        }

        var user_profile_url = '{{SITE_ROOT}}profile/' + encodeURIComponent(obj.user_email) + '/';

        var m = moment(obj.created_at);
        var data = $.extend({}, obj, {
            'content_marked': marked(obj.comment, {
                breaks: true,
                sanitize: true
            }),
            'time': m.format('LLLL'),
            'time_from_now': this.util_getRelativeTimeStr(m),
            'can_delete_msg': can_delete_msg,
            'user_profile_url': user_profile_url
        });

        var $item = $(this.itemTmpl(data));
        this.$listContainer.append($item);
    },

    scrollConToBottom: function() {
        var $el = $('.file-discussions-con', this.$el);
        $el.scrollTop($el[0].scrollHeight - $el[0].clientHeight);
    },

    replyTo: function(to_user) {
        var str = "@" + to_user + " ";
        var $input = this.$msgInput.val(str);
        setCaretPos($input[0], str.length);
        $input.trigger('focus');
    },

    // delete a comment
    delOne: function(item) { // item: {id:, $el:}
        var _this = this;
        $.ajax({
            url: '{{SITE_ROOT}}api2/repos/{{repo.id}}/file/comments/' + item.id + '/',
            type: 'delete',
            cache: false,
            beforeSend: prepareCSRFToken,
            success: function() {
                item.$el.remove();
                if ($('.msg', _this.$el).length == 0) {
                    _this.$emptyTip.show();
                    _this.$listContainer.hide();
                }
            },
            error: function(xhr) {
                var err_msg;
                if (xhr.responseText) {
                    err_msg = JSON.parse(xhr.responseText).error_msg;
                } else {
                    err_msg = "{% trans "Failed. Please check the network." %}";
                }
                feedback(err_msg, 'error');
            }
        });
    },

    util_getRelativeTimeStr: function(m) {
        var now = new Date();
        if (m - now > 0) {
            return "{% trans "Just now" %}";
        } else {
            return m.fromNow();
        }
    }
};
// init
fileDiscussions.init();

$('#discuss').on('click', function() {
    if (fileDiscussions.$el.is(':visible')) {
        fileDiscussions.hide();
    } else {
        fileDiscussions.show();
    }
});
$(document).on('keydown', function(e) {
    // ESCAPE key pressed
    if (e.which == 27) {
        fileDiscussions.hide();
    }
});

// for 'go back'
var $history = $('#history');
$history.attr('href', $history.attr('href') + '&referer=' + encodeURIComponent(location.href));
</script>
{% endblock %}
